package com.fortune.rainshine.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.code.kaptcha.impl.DefaultKaptcha;

/**
 * @ClassName: kaptchaRouter
 * @Description: 获取图形验证码
 * @author zhangxin
 * @date 2019年2月27日
 */
@Controller
@RequestMapping("imgcode")
public class kaptchaRouter {
	private final static Logger logger = LoggerFactory.getLogger(kaptchaRouter.class);
	@Autowired
	  private DefaultKaptcha defaultKaptcha;

	@GetMapping("imgcode")
    public void generateImgCode(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
      byte[] captchaChallengeAsJpeg;
      ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
      try {
        String createText = defaultKaptcha.createText();
        httpServletRequest.getSession().setAttribute("vercode", createText);
        
        BufferedImage challenge = defaultKaptcha.createImage(createText);
        ImageIO.write(challenge, "jpg", jpegOutputStream);

        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
      } catch (Exception e) {
    	logger.info("获取图形验证码失败",e);
    	e.printStackTrace();
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
      }

    }
	
}
